let form = layui.form;
let id = new URLSearchParams(location.search).get('id');
console.log(id);
// 渲染下拉框
$.ajax({
    url: '/my/category/list',
    // data: data,
    success: function (res) {
        console.log(res);
        let arr = []
        res.data.forEach(item => {
            arr.push(`<option value="${item.id}">${item.name}</option>`)
        })
        $('#xiala1').append(arr.join(''))
        form.render('select')


        // 数据回填
        $.ajax({

            url: '/my/article/' + id,
            success: function (res) {
                console.log(res)
                form.val('user', res.data);

                initEditor();

                image.cropper('destroy').attr('src', baseUrl + '/' + res.data.cover_img).cropper(option);
            }
        });
    }
})
// 渲染文本框
initEditor();

// 剪裁
let image = $('#image');
let option = {
    aspectRatio: 400 / 280,
    preview: '.img-preview'
};
image.cropper(option);

$('button:contains("选择封面")').on('click', function () {
    $('#file').trigger('click');
});

$('#file').on('change', function () {
    let files = this.files;
    if (files.length > 0) {
        let url = URL.createObjectURL(files[0]);
        // 删除,换图,添加
        image.cropper('destroy').attr('src', url).cropper(option);
    }
});

$('form').on('submit', function (e) {
    e.preventDefault();
    // 上传图片,必须用  FormData
    let fd = new FormData(this);
    fd.set('content', tinyMCE.activeEditor.getContent());
    let canvas = image.cropper('getCroppedCanvas', { width: 400, height: 280 });
    canvas.toBlob(blob => {
        // blob : 二进制大对象,图片的一种格式
        fd.append('cover_img', blob);
        $.ajax({
            type: 'post',
            url: '/my/article/add',
            data: fd,
            processData: false,
            contentType: false,
            success: function (res) {
                if (res.status == 0) {
                    layer.msg(res.message)
                    location.href = './list.html';
                } else {
                    layer.msg(res.message);
                }
            }
        });
    });
})
